import json
from http.server import BaseHTTPRequestHandler, HTTPServer
import socket
import urllib.parse
import ipaddress 
import http.client
from urllib.parse import urlparse

def native_get_request(url):
    # 解析 URL
    parsed_url = urlparse(url)
    host = parsed_url.netloc
    path = parsed_url.path or "/"
    if parsed_url.query:
        path += f"?{parsed_url.query}"

    # 创建 HTTP 连接（HTTPS 需改用 http.client.HTTPSConnection）
    conn = http.client.HTTPConnection(host)
    
    try:
        # 发送 GET 请求
        conn.request("GET", path)
        response = conn.getresponse()
        
        # 读取响应内容
        data = response.read().decode("utf-8")
        
        return {
            "status": response.status,
            "reason": response.reason,
            "headers": dict(response.getheaders()),
            "data": data
        }
    finally:
        conn.close()

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.handle_request("GET")

    def do_POST(self):
        self.handle_request("POST")

    def do_PUT(self):
        self.handle_request("PUT")

    def do_DELETE(self):
        self.handle_request("DELETE")

    def do_PATCH(self):
        self.handle_request("PATCH")

    def get_ip_geolocation(self,ip):
        """获取 IP 归属地信息（使用免费 API）"""
        try:
            response = native_get_request(f"http://ip-api.com/json/{ip}?fields=country,regionName,city,isp")
            return json.loads(response['data'])
        except:
            return {"error": "无法获取 IP 归属地"}

    def handle_request(self, method):
        # 1. 解析请求路径和查询参数
        parsed_path = urllib.parse.urlparse(self.path)
        query_params = urllib.parse.parse_qs(parsed_path.query)

        # 2. 解析请求体（仅处理 application/x-www-form-urlencoded 和 plain text）
        content_length = int(self.headers.get("Content-Length", 0))
        post_data = self.rfile.read(content_length).decode("utf-8")
        try:
            post_data = urllib.parse.parse_qs(post_data)  # 尝试解析 Form-Data
        except:
            pass  # 保留原始数据（如 JSON 或纯文本）

        # 3. 获取客户端 IP 和代理 IP
        client_ip = self.client_address[0]
        proxy_ip = self.headers.get("X-Forwarded-For", None)  # 代理场景

        # 4. 获取 IP 归属地（纯本地模拟，无第三方 API）
        ip_geolocation = self.get_ip_geolocation(client_ip)

        # 5. 构造响应数据
        response_data = {
            "client_ip": client_ip,
            "proxy_ip": proxy_ip,
            "ip_geolocation": ip_geolocation,
            "request_method": method,
            "path": self.path,
            "query_params": query_params,
            "post_data": post_data,
            "headers": dict(self.headers),
        }

        print('------------------------------------------------------------------')
        

        # 6. 返回 JSON 响应
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(response_data, indent=2).encode("utf-8"))
        print(f"client_ip: {client_ip}, proxy_ip: {proxy_ip}, ip_geolocation: {json.dumps(ip_geolocation)}")

    

if __name__ == "__main__":
    host = "0.0.0.0"
    port = 80
    server = HTTPServer((host, port), RequestHandler)
    print(f"Server running on http://{host}:{port}")
    server.serve_forever()
